package com.weixin.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.apache.struts2.ServletActionContext;
import org.dom4j.DocumentException;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.fenxiao.mytask.entity.UserTask;
import com.fenxiao.mytask.service.UserTaskService;
import com.fenxiao.record.entity.Commissionrecord;
import com.fenxiao.record.entity.FreeAmount;
import com.fenxiao.record.entity.IncomeRecode;
import com.fenxiao.record.service.CommissionrecordService;
import com.fenxiao.record.service.FreeAmountService;
import com.fenxiao.record.service.IncomeRecodeService;
import com.fenxiao.task.entity.Task;
import com.fenxiao.task.service.TaskService;
import com.fenxiao.user.entity.User;
import com.fenxiao.user.service.UserService;
import com.weixin.po.AccessToken;
import com.weixin.utils.CheckUtil;
import com.weixin.utils.MessageUtil;
import com.weixin.utils.Utils;
import com.weixin.utils.WeixinUtil;

public class WeixinServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private UserService userService;
	private UserTaskService userTaskService;
	private TaskService taskService;
	private CommissionrecordService commissionrecordService;
	private IncomeRecodeService incomeRecodeService;
	private FreeAmountService freeAmountService;
	private HttpServletRequest request;
	private HttpServletResponse response;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String code = req.getParameter("code");
		System.out.println(code);
		String signature = req.getParameter("signature");
		String timestamp = req.getParameter("timestamp");
		String nonce = req.getParameter("nonce");
		String echostr = req.getParameter("echostr");
		String mobile = req.getParameter("mobile");
		HttpSession session = req.getSession();
		System.out.println(session.getAttribute("openIdForever"));

		PrintWriter out = resp.getWriter();
		if (CheckUtil.checkSignature(signature, timestamp, nonce)) {
			out.print(echostr);
		}
	}

	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		try {
			req.setCharacterEncoding("UTF-8");
			resp.setCharacterEncoding("UTF-8");
			PrintWriter out = resp.getWriter();
			Map<String, String> map = MessageUtil.xmlToMap(req);
			String fromUserName = map.get("FromUserName");
			String toUserName = map.get("ToUserName");
			HttpServletRequest request = ServletActionContext.getRequest();
			String msgType = map.get("MsgType");
			String content = map.get("Content");
			Task task = null;
			String message = null;
			String weChatOfficialAccountReply = null;
			// String
			// message1="<xml><ToUserName><![CDATA[oI9OYxC-L155xx2xcJ_kkDZOEdgc]]></ToUserName><FromUserName><![CDATA[gh_cff59c08dcc2]]></FromUserName><CreateTime><![CDATA[1467342405527]]></CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[已经收到您的信息]]></Content></xml>";
			if (MessageUtil.MESSAGE_TEXT.equals(msgType)) {
				ServletContext servletContext = this.getServletContext();
				WebApplicationContext wac = null;
				wac = WebApplicationContextUtils
						.getRequiredWebApplicationContext(servletContext);
				this.userService = (UserService) wac.getBean("userService");
				this.userTaskService = (UserTaskService) wac
						.getBean("userTaskService");
				this.taskService = (TaskService) wac.getBean("taskService");
				this.commissionrecordService = (CommissionrecordService) wac
						.getBean("commissionrecordService");
				this.incomeRecodeService = (IncomeRecodeService) wac
						.getBean("incomeRecodeService");
				this.freeAmountService = (FreeAmountService) wac
						.getBean("freeAmountService");
				UserTask userTask1 = userTaskService.queryUserTaskByReply(
						content, toUserName);
				if (userTask1 != null) {
					
					Task task1=taskService.queryTaskById(userTask1.getTaskId());
					weChatOfficialAccountReply = MessageUtil.firstMenu();
					
					User user1 = userService.queryuserById(userTask1.getUser()
							.getId());
					
					
					String dateEnd=task1.getTaskEndTime();
					SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					Date dateEnd1=sdf1.parse(dateEnd);
					Date dateNow=new Date();
					
					String str=sdf1.format(dateNow); 
					if (userTask1.getTaskStatus() != 2&&task1.getTaskRemainderNumber()>0&&dateEnd1.getTime()>dateNow.getTime()) {
						userTaskService.updateWeChatReply(content,weChatOfficialAccountReply, toUserName);
								
						if(user1.getUserLevel()==1){
							taskService.updateTaskByMessage(userTask1.getTaskId(),userTask1.getTaskBonus());
						}
						if(user1.getUserLevel()==2){
							taskService.updateTaskByMessage(userTask1.getTaskId(),userTask1.getTaskBonus());
						}

						
						if (user1.getTaskNum() != null
								&& !"".equals(user1.getTaskNum())) {
							user1.setTaskNum(user1.getTaskNum() + 1);
						} else {
							user1.setTaskNum(1);
						}
						if (user1.getTotalMoney() != null
								&& !"".equals(user1.getTotalMoney())) {
							if(user1.getUserLevel()==1){
							user1.setTotalMoney(user1.getTotalMoney()+ userTask1.getTaskBonus());
							}
							if(user1.getUserLevel()==2){
								user1.setTotalMoney(user1.getTotalMoney()+ userTask1.getTaskBonus());
								}
						} else {
							if(user1.getUserLevel()==1){
								user1.setTotalMoney(user1.getTotalMoney()+ userTask1.getTaskBonus());
								}
								if(user1.getUserLevel()==2){
									user1.setTotalMoney(user1.getTotalMoney()+ userTask1.getTaskBonus());
									}
						}
						if (user1.getFreezingAmount() != null
								&& !"".equals(user1.getFreezingAmount())) {
							if(user1.getUserLevel()==1){
								user1.setTotalMoney(user1.getTotalMoney()+ userTask1.getTaskBonus());
								}
								if(user1.getUserLevel()==2){
									user1.setTotalMoney(user1.getTotalMoney()+ userTask1.getTaskBonus());
									}
						}
						if (user1.getTotalMoney() >= 3000) {
							user1.setUserLevel(2);
						}

						 userService.updateUser(user1);
						 User user2 = userService.queryUserSadff(user1.getRecomCode());
							if (user2 != null) {
								if (user1.getUserLevel() == 1) {
									double x1 = (userTask1.getTaskBonus() / 0.3) * 0.1;
									if (user2.getPromotionCommission() == null
											|| user2.getPromotionCommission() == 0) {
										user2.setPromotionCommission(x1);

									} else {
										user2.setPromotionCommission(user2.getPromotionCommission()
												+ x1);
									}
									if (user2.getTotalMoney() != null && !"".equals(user2.getTotalMoney())) {
										user2.setTotalMoney(user2.getTotalMoney()
												+ x1);
									} else {
										user2.setTotalMoney(x1);
									}
									Commissionrecord commissionrecord1 = new Commissionrecord();
									commissionrecord1.setRecordTime(str);
									commissionrecord1.setTaskTitle(userTask1.getTaskTitle());
									commissionrecord1.setTaskType(userTask1.getTaskType());
									commissionrecord1.setTaskMoney(x1);
									commissionrecord1.setRecordType(2);
									commissionrecord1.setUser(user2);
									commissionrecordService.addCommissionrecord(commissionrecord1);
								}
									double x2 = (userTask1.getTaskBonus() / 0.3) * 0.05;
									
									
									if (user2.getTeamCommissions() == null
											|| user2.getTeamCommissions() == 0) {
										user2.setTeamCommissions(x2);
									} else {
										user2.setTeamCommissions(user2.getTeamCommissions() + x2);
									}
									Commissionrecord commissionrecord2 = new Commissionrecord();
									commissionrecord2.setRecordTime(str);
									commissionrecord2.setTaskTitle(userTask1.getTaskTitle());
									commissionrecord2.setTaskType(userTask1.getTaskType());
									commissionrecord2.setTaskMoney(x2);
									commissionrecord2.setRecordType(2);
									commissionrecord2.setUser(user2);
									commissionrecordService.addCommissionrecord(commissionrecord2);
							}

					
						// 佣金记录 收入记录
						Commissionrecord commissionrecord = new Commissionrecord();
						
						commissionrecord.setRecordTime(str);
						commissionrecord.setTaskTitle(userTask1.getTaskTitle());
						commissionrecord.setTaskType(userTask1.getTaskType());
						if(user1.getUserLevel()==1){
							commissionrecord.setTaskMoney(userTask1.getTaskBonus());
							}
						if(user1.getUserLevel()==2){
							commissionrecord.setTaskMoney(userTask1.getTaskBonus());
							}
						
						
						
						commissionrecord.setRecordType(0);
						commissionrecord.setUser(user1);
						int c = commissionrecordService
								.addCommissionrecord(commissionrecord);
						/*IncomeRecode incomeRecode = new IncomeRecode();
						if(user1.getUserLevel()==1){
							incomeRecode.setIncomeMoney(userTask1.getTaskBonus());
							}
						if(user1.getUserLevel()==2){
							incomeRecode.setIncomeMoney(userTask1.getTaskBonus());
							}
						
						incomeRecode.setIncomeStatus(1);
						incomeRecode.setIncomeTime(str);
						incomeRecode.setUser(user1);
						int d = incomeRecodeService
								.addIncomeRecode(incomeRecode);*/
						FreeAmount freeAmount = new FreeAmount();
						freeAmount.setFreeStatus(1);
						freeAmount.setTaskMoney(userTask1.getTaskBonus());
						freeAmount.setTaskTitle(userTask1.getTaskTitle());
						freeAmount.setRecordTime(str);
						freeAmount.setUser(user1);
						Calendar cld = Calendar.getInstance();
						cld.set(Calendar.YEAR, dateNow.getYear());
						cld.set(Calendar.MONDAY, dateNow.getMonth());
						cld.set(Calendar.DATE, dateNow.getDay());
						cld.set(Calendar.HOUR, dateNow.getHours());
						cld.set(Calendar.MINUTE, dateNow.getMinutes());
						cld.set(Calendar.SECOND, dateNow.getSeconds());
						// 调用Calendar类中的add()，增加时间量
						cld.add(Calendar.DATE, 7);
						Date dt = cld.getTime();
						String sdt = sdf1.format(dt);
						freeAmount.setThawTime(sdt);
						freeAmount.setTaskType(userTask1.getTaskType());
						freeAmountService.addFreeAmount(freeAmount);
						message = MessageUtil.initText(toUserName, fromUserName,
								MessageUtil.firstMenu());
					}else if(task1.getTaskRemainderNumber()==0){
						message = MessageUtil.initText(toUserName, fromUserName,
								MessageUtil.first1Menu());
					}else if(dateEnd1.getTime()<dateNow.getTime()){
						message = MessageUtil.initText(toUserName, fromUserName,
								MessageUtil.first2Menu());
					}else if(userTask1.getTaskStatus() == 2){
						message = MessageUtil.initText(toUserName, fromUserName,
								MessageUtil.first3Menu());
					}
					
					System.out.println(message);
				} else if (task == null) {
					message = MessageUtil.initText(toUserName, fromUserName,
							MessageUtil.secondMenu());
				}
				if ("你好".equals(content)) {
					message = MessageUtil.initText(toUserName, fromUserName,
							MessageUtil.threeMenu());
				}
			} else if (MessageUtil.MESSAGE_EVNET.equals(msgType)) {
				String eventType = map.get("Event");
				if (MessageUtil.MESSAGE_SUBSCRIBE.equals(eventType)) {
					ServletContext servletContext = this.getServletContext();
					WebApplicationContext wac = null;
					wac = WebApplicationContextUtils
							.getRequiredWebApplicationContext(servletContext);
					this.userService = (UserService) wac.getBean("userService");

					message = MessageUtil.initNewsMessage(toUserName,
							fromUserName);
					AccessToken token = WeixinUtil.getAccessToken();
					String accessToken = token.getToken();
					String url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESSTOKEN&openid=OPENID";
					String requestUrl = url.replace("ACCESSTOKEN", accessToken)
							.replace("OPENID", fromUserName);
					JSONObject jsonObject = Utils.httpsRequest(requestUrl,
							"GET", null);

					String openId = jsonObject.getString("openid");
					User user1 = userService.queryMoneyOfUser(openId);
					if (user1 != null) {
						User user = new User();
						user.setWeChatId(jsonObject.getString("openid"));
						user.setNickName(jsonObject.getString("nickname"));
						user.setSex(jsonObject.getInt("sex"));
						user.setUserPhoto(jsonObject.getString("headimgurl"));
						/*
						 * user.setCountry(jsonObject.getString("country"));
						 * user.setProvince(jsonObject.getString("province"));
						 * user.setCity(jsonObject.getString("city"));
						 */
						Long subscribeTime = jsonObject
								.getLong("subscribe_time");

						SimpleDateFormat sdf = new SimpleDateFormat(
								"yyyy-MM-dd HH:mm:ss");
						String date = sdf
								.format(new Date(subscribeTime * 1000L));
						user.setRegTime(date);

						userService.updateUserForCompleteRegisteration(user);
					} else {
						User user = new User();
						user.setWeChatId(jsonObject.getString("openid"));
						user.setNickName(jsonObject.getString("nickname"));
						user.setSex(jsonObject.getInt("sex"));
						user.setUserPhoto(jsonObject.getString("headimgurl"));
						Long subscribeTime = jsonObject
								.getLong("subscribe_time");
						user.setSubscribe(1);
						SimpleDateFormat sdf = new SimpleDateFormat(
								"yyyy-MM-dd HH:mm:ss");
						String date = sdf
								.format(new Date(subscribeTime * 1000L));
						user.setRegTime(date);

						ServletContext servletContext1 = this
								.getServletContext();
						WebApplicationContext wac1 = null;
						wac1 = WebApplicationContextUtils
								.getRequiredWebApplicationContext(servletContext1);
						this.userService = (UserService) wac1
								.getBean("userService");
						userService.addUser(user);
					}

				} else if (MessageUtil.MESSAGE_UNSUBSCRIBE.equals(eventType)) {
					AccessToken token = WeixinUtil.getAccessToken();
					String accessToken = token.getToken();
					String url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESSTOKEN&openid=OPENID";
					String requestUrl = url.replace("ACCESSTOKEN", accessToken)
							.replace("OPENID", fromUserName);
					JSONObject jsonObject = Utils.httpsRequest(requestUrl,
							"GET", null);
					String openId = jsonObject.getString("openid");
					System.out.println(openId);
					ServletContext servletContext = this.getServletContext();
					WebApplicationContext wac = null;
					wac = WebApplicationContextUtils
							.getRequiredWebApplicationContext(servletContext);
					this.userService = (UserService) wac.getBean("userService");
					userService.updateUpdateUnsubscribe(openId);
				} else if (MessageUtil.MESSAGE_CLICK.equals(eventType)) {
					message = MessageUtil.initText(toUserName, fromUserName,
							MessageUtil.menuText());
				} else if (MessageUtil.MESSAGE_VIEW.equals(eventType)) {
					String url = map.get("EventKey");
					message = MessageUtil.initText(toUserName, fromUserName,
							url);
				} else if (MessageUtil.MESSAGE_SCANCODE.equals(eventType)) {
					String key = map.get("EventKey");
					String event = map.get("Event");
					String ScanCodeInfo = map.get("ScanCodeInfo");
					System.out.println(ScanCodeInfo);
					message = MessageUtil.initText(toUserName, fromUserName,
							ScanCodeInfo);
				}
			} else if (MessageUtil.MESSAGE_LOCATION.equals(msgType)) {
				String label = map.get("Label");
				message = MessageUtil.initText(toUserName, fromUserName, label);
			}

			System.out.println(message);

			out.print(message);
		} catch (DocumentException e) {
			e.printStackTrace();
		}/*
		 * finally{ out.close(); }
		 */ catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public HttpServletRequest getRequest() {
		return request;
	}

	public void setRequest(HttpServletRequest request) {
		this.request = request;
	}

	public HttpServletResponse getResponse() {
		return response;
	}

	public void setResponse(HttpServletResponse response) {
		this.response = response;
	}

}
